package cn.tannn.ops.ssh.controller;

import cn.tannn.jdevelops.annotations.web.mapping.PathRestController;
import cn.tannn.jdevelops.exception.built.BusinessException;
import cn.tannn.jdevelops.result.response.ResultVO;
import cn.tannn.ops.ssh.entity.SshInfo;
import cn.tannn.ops.ssh.pojo.UsePortInfo;
import cn.tannn.ops.ssh.service.SshInfoService;
import cn.tannn.ops.util.PortUtil;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.io.IOException;
import java.util.List;

/**
 * 端口管理
 *
 * @author <a href="https://t.tannn.cn/">tan</a>
 * @version V1.0
 * @date 2024/12/26 15:30
 */
@PathRestController("/ssh/port")
@Slf4j
@Tag(name = "服务器端口信息")
@RequiredArgsConstructor
public class PortController {

    private final SshInfoService sshInfoService;

    @GetMapping("/use/{sshId}")
    @Operation(summary = "被占用端口", description = "被用了")
    @Parameter(name = "sshId", description = "ssh连接信息的ID")
    public ResultVO<List<UsePortInfo>> usePort(@PathVariable("sshId") Long sshId) {
        SshInfo sshInfo = sshInfoService
                .findOnly("id", sshId)
                .orElseThrow(() -> new BusinessException("请选择正确的服务器"));
        try {
            Session session = sshInfo.session();
            return ResultVO.success(PortUtil.findPortUseInfo(session));
        } catch (JSchException | IOException e) {
            if(e.getMessage().contains("Auth fail")){
                throw new BusinessException("服务器验证失败", e);
            }else {
                throw new BusinessException("服务器连接失败", e);
            }
        }
    }


}
